import React, { ComponentType, useEffect, useState } from 'react';
import { Menu } from 'antd';
import { NavLink, withRouter, RouteComponentProps } from 'react-router-dom';

export interface IRoute {
    path: string;
    /** 是否精准匹配 */
    exact?: boolean;
    component?: ComponentType<any>;
    redirect?: string;
    label?: string;
    icon?: string;
    isMenu?: boolean;
    children?: IRoute[];
}
interface IProps extends RouteComponentProps {
    routes: IRoute[];
}

const { SubMenu } = Menu;

const Aside = (props: IProps) => {
    const { location, routes } = props;
    const [selectKeys, setSelectKeys]: [string[], any] = useState([]);
    const [openKeys, setOpenKeys]: [string[], any] = useState([]);

    useEffect(() => {
        const tempKeys: string[] = [];
        const pathArr = location.pathname.split('/');
        pathArr.forEach((item, i) => {
            const prePath = pathArr[i - 1];
            tempKeys.push(prePath ? `/${prePath}/${item}` : `/${item}`);
        });
        setSelectKeys(tempKeys);
        setOpenKeys(tempKeys);
    }, [location.pathname]);
    return (
        <Menu
            theme="light"
            mode="inline"
            onOpenChange={newOpenKeys => {
                setOpenKeys(newOpenKeys);
            }}
            selectedKeys={selectKeys}
            openKeys={openKeys}
            inlineIndent={12}
        >
            {routes
                .filter(item => !item.redirect)
                .map(item => {
                    if (item.children && item.children.length > 0) {
                        return (
                            <SubMenu key={item.path} title={item.label}>
                                {item.children
                                    .filter(i => i.isMenu)
                                    .map(menu => (
                                        <Menu.Item
                                            key={menu.path}
                                        >
                                            <NavLink to={menu.path}>
                                                <span>{menu.label}</span>
                                            </NavLink>
                                        </Menu.Item>
                                    ))}
                            </SubMenu>
                        );
                    }
                    if (item.isMenu) {
                        return (
                            <Menu.Item key={item.path}>
                                <NavLink to={item.path}>
                                    <span>{item.label}</span>
                                </NavLink>
                            </Menu.Item>
                        );
                    }
                    return null;
                })}
        </Menu>
    );
};

export default withRouter(Aside);
